import React from 'react';
import { isEqual } from 'lodash';
import {WeaTools, WeaErrorPage, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
//自定义页面元素
class Iframe extends React.Component {
    constructor(props) {
        super(props);
        this.setFrameData = this.setFrameData.bind(this);
        this.wirteDataToFrame = this.wirteDataToFrame.bind(this);
    }
    setFrameData(curProps){
        let that = this;
        const { eid, data, tabid, isSetting, requestid } = curProps;
        $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr({
            scrolling: "auto",
            noresize: "noresize",
            border: "0"
        });
        let ifrmUrl = data.url;
        if (ifrmUrl) {
            if (requestid && parseInt(requestid) != -1) {
              ifrmUrl += ifrmUrl.indexOf('?') != -1 ? `&requestid=${requestid}` : `?requestid=${requestid}`;
            }
            ifrmUrl = ifrmUrl.replace(/(jsp#)|(html#)/g, (item) => item.replace(/(jsp)|(html)/g, (type) => `${type}?__random__=${window.Date.now()}`));

            if (ifrmUrl.indexOf("http://") == 0 || ifrmUrl.indexOf("https://") == 0 || data.showtype != '2') {
                var srcUrl = $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr("src");
                $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr({ src: ifrmUrl });
            } else {
                $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr({ src: 'about:blank' });
                var arr = ifrmUrl.split(".");
                var last = arr[arr.length - 1]
                const index = last.indexOf("htm");
                const ifrmsdata = ls.getStr("custompage-" + eid + "-" + tabid);
                let aa = ifrmsdata ? true : false;
                if (ifrmsdata) {
                    //解决刷新加载缓存空白的问题
                    that.wirteDataToFrame(ifrmsdata, eid, isSetting);
                    //解决改变url或URL返回的内容改变时不更新的问题
                    $.ajax({
                        type: "GET",
                        url: ifrmUrl,
                        dataType: "html",
                        success: function(data) {
                            //判断返回的数据是否有变化，有的话更新缓存并重新渲染
                            if (data !== ifrmsdata) {
                                ls.set("custompage-" + eid + "-" + tabid, data);
                                that.wirteDataToFrame(data, eid, isSetting);
                            }
                        },
                        error: function(xhr) {
                            that.wirteDataToFrame(xhr.responseText, eid, isSetting);
                        }
                    });
                } else {
                    $.ajax({
                        type: "GET",
                        url: ifrmUrl,
                        dataType: "html",
                        success: function(data) {
                            if (index >= 0) {
                                ls.set("custompage-" + eid + "-" + tabid, data);
                            }
                            that.wirteDataToFrame(data, eid, isSetting);
                        },
                        error: function(xhr) {
                            that.wirteDataToFrame(xhr.responseText, eid, isSetting);
                        }
                    });

                }
            }
        }else{
            $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr({ src: 'about:blank' }); 
        }
    }
    wirteDataToFrame(data, eid, isSetting){
        let _ifrm = $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid)[0];
        if(_ifrm){
            _ifrm.contentWindow.document.write(data)
            _ifrm.contentWindow.document.close()
            try {
                _ifrm.contentWindow.customPageInit()
            } catch (e) {}
        }
    }
    shouldComponentUpdate(nextProps){
        return !nextProps.refresh
    }
    componentDidUpdate() {
        if(!this.props.refresh){
            try {
                function f() {
                    let _ifrm = $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid)[0];
                    if(_ifrm){
                        _ifrm.contentWindow.document.write("")
                        _ifrm.contentWindow.document.close()
                    }
                }{this.setFrameData(this.props)}
            }catch (e) {}
        }
    }
    componentDidMount() {
        const { eid, config={} } = this.props;
        const { layoutid, areaflag, subCompanyId } = config;
        if(!this.props.refresh) {
            try {
                this.setFrameData(this.props);
            }catch (e) {}
        }
    }
    componentWillUnmount() {
        const { eid, isSetting } = this.props;
        $(".homepage[data-issetting="+isSetting+"]").find("#ifrm_" + eid).attr({src:'about:blank'});
    }
    render() {
        const { eid, data, tabid, refresh, cstyle } = this.props;
        let html = <iframe id={`ifrm_${eid}`}
            frameBorder="no" 
            className="custompageIframe" 
            height={data.height == '' ? parseInt(cstyle.height)+ '' : data.height}
            src="about:blank" 
            style={{borderCollapse:'collapse',width:'100%', display: 'block'}}
            name={`ifrm_${eid}`}/>
        return <div>{html}</div>
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@yxxmhb`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！")} />
        );
    }
}

Iframe = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Iframe);
export default Iframe;

